package cn.easybuy.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easybuy.entity.Product;
import cn.easybuy.entity.ProductCategory;
import cn.easybuy.service.ProductCategoryService;
import cn.easybuy.service.ProductService;
import cn.easybuy.service.impl.ProductCategoryServiceImpl;
import cn.easybuy.service.impl.ProductServiceImpl;

/**
 * 初始化首页信息
 */
@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
	
	ProductCategoryService pcService =null;
	ProductService productService =null;
	
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		//初始化几个service
		pcService = new ProductCategoryServiceImpl();
		productService = new ProductServiceImpl();
	} 
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("------销毁前");
		super.destroy();
		System.out.println("------销毁后----");
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("---------------进入了HomeServlet 初始首页信息");
		
		List<ProductCategory> pclist = pcService.getAllProductCategroy();
		
		
		//获取每个品类下的6笔商品信息
		//pclist 里面有6 个类别 化妆品, 保健食品, 进口食品,生鲜, 箱包, 电子商品, 家用商品
		// 而 化妆品底下又有6个商品 List<Product> list1 
		// 家用商品 底下也有6个商品 List<Product> list2 
		//list中不能再包含list
		//借助Map来实现
		Map<Integer,List<Product>> productMaps =new HashMap<Integer,List<Product>>();
		
		for (ProductCategory pc : pclist) {
			int pcId = pc.getId();//[存这些类别的id  化妆品, 保健食品, 进口食品,生鲜, 箱包, 电子商品, 家用商品]
		
			//按父类Id 查找对应的6款商品 ,存入List中
			List<Product> list = productService.getAllProductByCategoryId(pcId);
			
			productMaps.put(pcId, list);
		}
		
		request.setAttribute("pclist", pclist);
		request.setAttribute("productMaps", productMaps);
		System.out.println("pclist.size: "+ pclist.size());
		//页面跳转至首页
		request.getRequestDispatcher("Index.jsp").forward(request, response);
		
		
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
